package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.entity.User;
import com.echo.exception.ArticleException;
import com.echo.service.ArticleService;
import com.echo.servlet.BaseServlet;
import com.echo.util.SessionUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 删除文章Servlet：处理/deleteArticle请求
 */
@WebServlet({"/deleteArticle", "/echo-network/deleteArticle"})
public class DeleteArticleServlet extends BaseServlet {
    private final ArticleService articleService = new ArticleService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 校验登录状态（未登录重定向到登录页）
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect("/echo-network/login.html");
            return;
        }

        // 2. 获取文章ID
        String articleIdStr = request.getParameter("id");
        if (articleIdStr == null || articleIdStr.isEmpty()) {
            request.getSession().setAttribute("errorMsg", "文章ID不能为空");
            response.sendRedirect("/echo-network/article-show");
            return;
        }

        try {
            Integer articleId = Integer.parseInt(articleIdStr);
            
            // 3. 校验权限（确保是作者本人或管理员才能删除）
            Article existingArticle = articleService.findById(articleId);
            if (existingArticle == null) {
                request.getSession().setAttribute("errorMsg", "文章不存在");
                response.sendRedirect("/echo-network/article-show");
                return;
            }
            
            // 检查是否是管理员或者文章作者
            boolean isAdmin = loginUser.getRole() == 1; // 1表示管理员
            boolean isAuthor = existingArticle.getAuthorUsername().equals(loginUser.getUsername());
            
            if (!isAdmin && !isAuthor) {
                request.getSession().setAttribute("errorMsg", "无权删除此文章");
                response.sendRedirect("/echo-network/article-show");
                return;
            }

            // 4. 调用Service删除文章
            articleService.delete(articleId);

            // 5. 删除成功：设置成功提示并重定向到我的文章页
            request.getSession().setAttribute("successMsg", "文章删除成功！");
            response.sendRedirect("/echo-network/article-show");

        } catch (NumberFormatException e) {
            request.getSession().setAttribute("errorMsg", "无效的文章ID");
            response.sendRedirect("/echo-network/article-show");
        } catch (ArticleException e) {
            // 业务异常：显示具体错误信息
            e.printStackTrace();
            request.getSession().setAttribute("errorMsg", e.getMessage());
            response.sendRedirect("/echo-network/article-show");
        } catch (SQLException e) {
            // 数据库异常：显示系统错误
            e.printStackTrace();
            request.getSession().setAttribute("errorMsg", "系统错误，文章删除失败");
            response.sendRedirect("/echo-network/article-show");
        }
    }
}